package com.example.su_shi_tan_bas_lib.album.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.camera.core.*
import androidx.camera.core.ImageCapture.OutputFileOptions
import androidx.camera.view.CameraView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.library_common.album.ui.AlbumCapturedListFragment
import com.example.library_common.album.ui.AlbumPreviewFragment
import com.example.su_shi_tan_bas_lib.album.constant.FILE_SCAN
import com.example.library_common.album.utils.ALBUM_SELECT_REFRESH
import com.example.su_shi_tan_bas_lib.album.bean.AlbumFile
import com.example.su_shi_tan_bas_lib.album.bean.FunctionBean
import com.example.su_shi_tan_bas_lib.album.constant.AlbumMedia
import com.example.su_shi_tan_bas_lib.album.interfaces.AlbumPanelNode
import com.example.su_shi_tan_bas_lib.album.utils.AlbumTakePhotoSound
import com.example.su_shi_tan_bas_lib.album.view.RecordView
import com.example.su_shi_tan_bas_lib.base.BaseDataBindingFragment
import com.example.su_shi_tan_bas_lib.databinding.AlbumFragmentCameraLayoutBinding
import com.example.su_shi_tan_bas_lib.utils.FileUtil
import com.example.su_shi_tan_bas_lib.utils.even.MessageWrap
import java.io.File

import com.example.su_shi_tan_bas_lib.R


class AlbumCameraFragment : BaseDataBindingFragment<AlbumFragmentCameraLayoutBinding>(),
    View.OnClickListener, RecordView.onRecordListener {

    companion object {

        @JvmStatic
        fun newInstance(): AlbumCameraFragment {
            val args = Bundle()
            val fragment = AlbumCameraFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private val albumFolder = "albumFolder"

    private var funBean: FunctionBean? = null

    private val mAlbumCaptured = AlbumCapturedListFragment.newInstance()

    //
    private var maxSelectedCount = FunctionBean.MIN_SELECT_COUNT
//
//    private lateinit var shootMP: MediaPlayer


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        AlbumTakePhotoSound.getInstance().initPool(_mActivity)
//
//
//        val parse = Uri.parse("file:///system/media/audio/ui/camera_click.ogg")
//
//        shootMP = MediaPlayer.create(_mActivity, parse)
//
        val parentFragment = parentFragment

        if (parentFragment is AlbumPanelNode) {
            funBean = (parentFragment as AlbumPanelNode).functionBean
            maxSelectedCount = funBean?.selectCount ?: maxSelectedCount
            mAlbumCaptured.setFunBean(funBean)
        }
    }

    override fun layoutId() = R.layout.album_fragment_camera_layout

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewBinder.onViewClick = this

        loadRootFragment(R.id.mCaptured, mAlbumCaptured)
    }

    override fun onLazyInitView(savedInstanceState: Bundle?) {
        super.onLazyInitView(savedInstanceState)
        val captureType =
            when (funBean?.mediaType) {
                AlbumMedia.MEDIA_FOR_IMAGE -> RecordView.ONLY_CAPTURE_IMG
                AlbumMedia.MEDIA_FOR_VIDEO -> RecordView.ONLY_CAPTURE_VIDEO
                AlbumMedia.MEDIA_FOR_ALL -> RecordView.ONLY_CAPTURE_ALL
                else -> RecordView.ONLY_CAPTURE_ALL
            }

        viewBinder.controlView.setCaptureType(captureType)

        viewBinder.controlView.setOnRecordListener(this)

        viewBinder.controlView.setEnableRecording(
            (funBean?.checkedFiles?.size ?: 0) <= maxSelectedCount
        )

//        viewBinder.controlView.setOnRecordListener(this)

        if (ActivityCompat.checkSelfPermission(
                _mActivity,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {

            return
        }
        viewBinder.mCameraView.captureMode =
            when (funBean?.mediaType) {
                AlbumMedia.MEDIA_FOR_IMAGE -> CameraView.CaptureMode.IMAGE
                AlbumMedia.MEDIA_FOR_VIDEO -> CameraView.CaptureMode.VIDEO
                AlbumMedia.MEDIA_FOR_ALL -> CameraView.CaptureMode.MIXED
                else -> CameraView.CaptureMode.MIXED
            }
        viewBinder.mCameraView.bindToLifecycle(this)

        flashHandUi(false)

        swCameraHand(false)
    }


    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.backPage -> pop()

            R.id.flashBtn -> {
                flashHandUi(true)
            }

            R.id.swCamera -> {
                swCameraHand(true)
            }
            R.id.torchBtn -> {
                p0.isSelected = !p0.isSelected
                torchHand()
            }
        }
    }

    private fun torchHand() {
        if (viewBinder.torchBtn.isSelected) {
            viewBinder.mCameraView.enableTorch(true)
            viewBinder.flashBtn.visibility = View.GONE
        } else {
            viewBinder.mCameraView.enableTorch(false)
            viewBinder.flashBtn.visibility = View.VISIBLE
        }
    }

    /**
     *前后摄像头切换
     **/
    private fun swCameraHand(funChanged: Boolean) {

        var drawableColor = 0

        var lensFacing = -100

        when (viewBinder.mCameraView.cameraLensFacing) {
            CameraSelector.LENS_FACING_BACK -> {
                drawableColor = ContextCompat.getColor(_mActivity, R.color.PrimaryColor)
                lensFacing = CameraSelector.LENS_FACING_FRONT
            }
            CameraSelector.LENS_FACING_FRONT -> {
                drawableColor = Color.WHITE
                lensFacing = CameraSelector.LENS_FACING_BACK
            }
        }


        if (drawableColor != 0) {
            viewBinder.swCamera.setColorFilter(drawableColor)
        }

        if (lensFacing >= 0 && funChanged) {
            viewBinder.swCamera.setColorFilter(drawableColor)
            viewBinder.mCameraView.cameraLensFacing = lensFacing
        }

    }


    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        if (msg?.message == ALBUM_SELECT_REFRESH) {
            val checkedFiles = funBean?.checkedFiles
            if (checkedFiles?.isEmpty() == true) {
                viewBinder.mCaptured.visibility=View.GONE
            }
        }
    }

    /**
     * 闪光灯Ui处理
     **/
    private fun flashHandUi(funChang: Boolean) {
        var flashDrawable = 0
        var flashMod = -100
        when (viewBinder.mCameraView.flash) {
            ImageCapture.FLASH_MODE_AUTO -> {
                flashMod = ImageCapture.FLASH_MODE_ON
                flashDrawable = R.drawable.ic_baseline_flash_auto_24
            }
            ImageCapture.FLASH_MODE_ON -> {

                flashMod = ImageCapture.FLASH_MODE_OFF
                flashDrawable = R.drawable.ic_baseline_flash_on_24
            }
            ImageCapture.FLASH_MODE_OFF -> {

                flashMod = ImageCapture.FLASH_MODE_AUTO
                flashDrawable = R.drawable.ic_baseline_flash_off_24
            }

        }

        if (flashDrawable != 0) {
            viewBinder.flashBtn.setImageResource(flashDrawable)
        }

        if (funChang && flashMod >= 0) {
            viewBinder.mCameraView.flash = flashMod
        }
    }

    private fun toTakePic() {
        val fileFolder = FileUtil.createDir("app_img")
        val addDate = System.currentTimeMillis()
        val mimeType = "jpeg"
        val file = File(fileFolder, "$addDate.$mimeType")
        val outputFileOptions = OutputFileOptions.Builder(file).build()

        viewBinder.mCameraView.takePicture(
            outputFileOptions,
            ContextCompat.getMainExecutor(_mActivity),
            object : ImageCapture.OnImageSavedCallback {
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {

//                    val msg = "图片保存成功: ${file.absolutePath}"
//                    Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()

//                    val mImagePathUri = FileProviderHelper.getFormFileUri(_mActivity,file)
                    AlbumTakePhotoSound.getInstance().playVoice(1)

                    saveFile(file, mimeType, addDate)

//                    shootSound()


//                    viewBinder.shootRefreshView.reset()
                }

                override fun onError(exception: ImageCaptureException) {

                    val msg = "图片保存失败: ${exception.message}"
                    Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
//                    viewBinder.shootRefreshView.reset()
                }
            }
        )
    }

    private fun saveFile(file: File, mimeType: String, addDate: Long) {
        val imageFile = AlbumFile()
        imageFile.mediaType = AlbumFile.TYPE_IMAGE
        imageFile.path = file.absolutePath
        imageFile.bucketName = albumFolder
        imageFile.mimeType = mimeType
        imageFile.addDate = addDate
        imageFile.latitude = 0f
        imageFile.longitude = 0f
        imageFile.size = file.length()
        imageFile.isChecked = true
        funBean?.checkedFiles?.add(imageFile)

        mAlbumCaptured.addAlbumFile(imageFile)

        viewBinder.mCaptured.visibility = View.VISIBLE

        viewBinder.controlView.setEnableRecording(funBean?.checkedFiles?.size ?: 0 <= maxSelectedCount)

        sndSysBroadcast(file)
    }

    fun shootSound() {
//        val audio =
//            _mActivity.getSystemService(Context.AUDIO_SERVICE) as AudioManager
//
//        val volume = audio.getStreamVolume(AudioManager.STREAM_NOTIFICATION)
//        if (volume == 0) {
//            audio.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 2, 0)
//        }
//
//        shootMP.start()
//
//        audio.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0)
    }

    private fun sndSysBroadcast(file: File) {
        val contentFileUri: Uri = Uri.fromFile(File(file.absolutePath))
        val mediaScanIntent =
            Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentFileUri)
        _mActivity.sendBroadcast(mediaScanIntent)

        val local =
            Intent(FILE_SCAN)
        _mActivity.sendBroadcast(local)
    }


    override fun onDestroy() {
        super.onDestroy()
//        shootMP.release()
    }


    private fun toRecordVideo() {

        val createDirs = FileUtil.createDir("app_video")
        val mimeType = "mp4"
        val addDate = System.currentTimeMillis()
        val videoFile = File(createDirs, "${addDate}.${mimeType}")
        if (!videoFile.exists()) {
            videoFile.createNewFile()
        }
        viewBinder.mCameraView.startRecording(videoFile,
            ContextCompat.getMainExecutor(_mActivity),
            object : VideoCapture.OnVideoSavedCallback {
//                override fun onVideoSaved(file: File) {
//
//                    Toast.makeText(
//                        _mActivity,
//                        "录制成功${file.absoluteFile}",
//                        Toast.LENGTH_SHORT
//                    ).show()
//
//                    saveFile(file, mimeType, addDate)
//
//                    viewBinder.mCameraView.stopRecording()
//                }

                override fun onVideoSaved(outputFileResults: VideoCapture.OutputFileResults) {
//                    val savedUri = outputFileResults.savedUri?: Uri.fromFile(videoFile)
                    Toast.makeText(
                        _mActivity,
                        "录制成功${videoFile.absoluteFile}",
                        Toast.LENGTH_SHORT
                    ).show()

                    saveFile(videoFile, mimeType, addDate)

                    viewBinder.mCameraView.stopRecording()

                }

                override fun onError(videoCaptureError: Int, message: String, cause: Throwable?) {
                    Toast.makeText(_mActivity, "录制失败", Toast.LENGTH_SHORT).show()
                    Log.d("onError", "onError: $message")
                    Log.d("onError", "onError: ${cause.toString()}")
                }

            }
        )


    }


    override fun onClick() {
        if (funBean?.checkedFiles?.size ?: 0 >= maxSelectedCount) {
            Toast.makeText(
                _mActivity,
                "最多拍${maxSelectedCount}张",
                Toast.LENGTH_SHORT
            ).show()

            val mPreviewFragment = AlbumPreviewFragment.newInstance()
            mPreviewFragment.setCurrentIndex(0)
//             if (parentFragment !=null){
//                 ( parentFragment as BaseFragmentEx).supportDelegate.replaceFragment(mPreviewFragment,false)
//             }
            start(mPreviewFragment)
            return
        }
        toTakePic()
    }

    override fun onFinish() {
        viewBinder.mCameraView.stopRecording()
    }

    override fun onLongClick() {
        if (funBean?.checkedFiles?.size ?: 0 >= maxSelectedCount) {
            Toast.makeText(
                _mActivity,
                "最多拍摄${maxSelectedCount}部",
                Toast.LENGTH_SHORT
            ).show()
            return
        }

        toRecordVideo()
    }

    override fun onError() {

    }

}